#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "Logger.hpp"

Logger& Log = Logger::GetInstance(); //日志

//退出错误码
enum
{
    SOCK_FAILED = 1,
    BIND_FAILED = 2
};

//<---      全局变量       --->
using ServerFunction = std::function<std::string(const std::string &)>;
const uint16_t portDefault = 8080;      //默认端口号
const std::string IPDefault("0.0.0.0"); //默认IP

//服务器类
class UdpServer
{
public:
    UdpServer(const uint16_t &port = portDefault, const std::string &IP = IPDefault)
        : _port(port), _IP(IP), _sockfd(0), _isRunning(false) {}

    ~UdpServer()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

    void Init()
    {
        //创建UDP套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            Log(Fatal, "socket filled");
            exit(SOCK_FAILED);
        }

        //绑定到系统
        struct sockaddr_in localSockaddr;
        memset(&localSockaddr, 0, sizeof(localSockaddr)); //将结构体置空
        //初始化结构体
        localSockaddr.sin_family = AF_INET;                     //IPv4
        localSockaddr.sin_port = htons(_port);                  //端口号
        localSockaddr.sin_addr.s_addr = inet_addr(_IP.c_str()); //转换IP地址
        //绑定开始
        if (bind(_sockfd, (const struct sockaddr *)&localSockaddr, sizeof(localSockaddr)) < 0)
        {
            Log(Fatal, "Bind failed");
            exit(BIND_FAILED);
        }
    }

    //接收到用户的消息并打印，重复返回给顾客
    void Run(ServerFunction func)
    {
        _isRunning = true;
        char buffer[1024];

        while (_isRunning)
        {
            //定义客户套接字
            struct sockaddr_in client;
            memset(&client, 0, sizeof(client));

            socklen_t lenClient = sizeof(client); //client大小的变量
            ssize_t ret_num = 0;
            ret_num = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &lenClient);
            if (ret_num < 0)
            {
                Log(Warning, "recvfrom failed");
                continue;
            }
            //处理信息
            std::string ret_string(buffer, ret_num);
            std::string server_response(func(ret_string));

            //发送回去给客户端
            ssize_t send_num = 0;
            send_num = sendto(_sockfd, server_response.c_str(), server_response.size(), 0, (const sockaddr *)&client, lenClient);
            if(send_num < 0){
                Log(Warning, "sendto failed");
                continue;
            }
        }
    }

private:
    uint16_t _port;  //端口号
    std::string _IP; //IP
    int _sockfd;     //套接字描述符
    bool _isRunning;
};